﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CourseManagerBLL;
using CourseManagerModels;
namespace CourseManagerUI
{
	public partial class FrmCourseManage : Form
	{
		private CourseCategoryManager courseCategoryManager = new CourseCategoryManager();
		private CourseManager courseManager = new CourseManager();
		private List<Course> queryList = null;//创建一个集合，用来缓存查询结果，便于后面修改和删除使用，从而减少数据库的访问
		public FrmCourseManage()
		{
			InitializeComponent();
			List<CourseCategory> list = courseCategoryManager.GetCourseCategories();
			//在集合第一个位置插入空白
			list.Insert(0, new CourseCategory { CategoryId = -1, CategoryName = "-请选择-" });

			//设置下拉框数据源
			this.CourseTypeComBox.DataSource = list;
			//设置展示给用户的数据(CourseCategory.cs中的字段名)
			this.CourseTypeComBox.DisplayMember = "CategoryName";
			//设置用户选择后传递的值
			this.CourseTypeComBox.ValueMember = "CategoryId";

			//禁止自动生成列
			this.CourseDataGridView.AutoGenerateColumns = false;
			//隐藏修改面板
			this.panel1.Visible = false;
			//禁用修改和删除按钮,未选择课程无法修改和删除
			this.ChangeCourseBtn.Enabled = this.DeleteCourseBtn.Enabled = false;


			//绑定修改用的课程分类
			//  this.cbbCategory_Modify.DataSource = list;//如果直接使用前面的集合，会造成两个下拉框联动
			this.CourseTypeComBox1.DataSource = new List<CourseCategory>(list);//将前面的集合重新复制后再做数据源
			this.CourseTypeComBox1.DisplayMember = "CategoryName";
			this.CourseTypeComBox1.ValueMember = "CategoryId";
		}

		//提交查询
		private void CommitQueryBtn_Click(object sender, EventArgs e)
		{
			//【1】条件验证
			//未选择或者选择了--默认类别 且 课程名字也为空，则返回
			if ((this.CourseTypeComBox.SelectedIndex == -1 || this.CourseTypeComBox.SelectedIndex == 0)
				&& this.CourseNameTextBox.Text.Trim().Length == 0)
			{
				MessageBox.Show("请至少选择一个查询条件！", "查询提示");
				return;
			}


			int categoryId = this.CourseTypeComBox.SelectedIndex == -1 ? -1 : Convert.ToInt32(this.CourseTypeComBox .SelectedValue);
			queryList = courseManager.QueryCourse(categoryId, this.CourseNameTextBox.Text.Trim());

			//【3】展示查询
			if (queryList.Count == 0) //如果没有找到结果，清空上一次查询的数据
			{
				this.QueryResultLabel.Text = "0";
				this.CourseDataGridView.DataSource = null;
				this.ChangeCourseBtn.Enabled = this.DeleteCourseBtn.Enabled = false;
				MessageBox.Show("没有找到查询结果！", "查询提示");
			}
			else  //重新绑定查询结果
			{
				this.CourseDataGridView.DataSource = queryList;
				this.QueryResultLabel.Text = this.CourseDataGridView.RowCount.ToString();
				this.ChangeCourseBtn.Enabled = this.DeleteCourseBtn.Enabled = true;
			}
			this.panel1.Visible = false;//每次查询都要隐藏修改面板，提高用户体验
		}

		//修改课程
		private void ChangeCourseBtn_Click(object sender, EventArgs e)
		{
			if (this.CourseDataGridView.CurrentRow == null)
			{
				MessageBox.Show("请首先选择一行！", "修改提示");
				return;
			}
			//【1】获取当前选中行的对应的课程ID
			int courseId = (int)this.CourseDataGridView.CurrentRow.Cells["CourseId"].Value;
			//【2】根据课程ID从集合中查询课程对象
			Course currentCourse = null;
			currentCourse = (from c in this.queryList where c.CourseId.Equals(courseId) select c).First();
			// currentCourse = this.queryList.Where(c => c.CourseId.Equals(courseId)).First();

			//【3】显示要修改的课程对象
			this.CourseNameTextBox1.Text = currentCourse.CourseName;
			this.CourseCreditTextBox.Text = currentCourse.Credit.ToString();
			this.CourseNumberTextBox.Text = currentCourse.ClassHour.ToString();
			this.CourseContentTextBox.Text = currentCourse.CourseContent;
			this.CourseNoLabel.Text = currentCourse.CourseId.ToString();//为提交修改使用

			//将当前课程分类和下拉框选择做同步
			this.CourseTypeComBox1.SelectedValue = currentCourse.CategoryId;
			this.panel1.BringToFront();
			this.panel1.Visible = true;
		}

		//保存修改
		private void CommitChangeBtn_Click(object sender, EventArgs e)
		{
			//【1】数据验证：对要修改的信息检查

			//【2】封装对象
			Course course = new Course
			{
				CourseName = this.CourseNameTextBox1.Text.Trim(),
				CourseContent = this.CourseContentTextBox.Text.Trim(),
				ClassHour = Convert.ToInt32(this.CourseNumberTextBox.Text.Trim()),
				Credit = Convert.ToInt32(this.CourseCreditTextBox.Text.Trim()),
				CategoryId = Convert.ToInt32(this.CourseTypeComBox1.SelectedValue),
				TeacherId = Program.currentTeacher.TeacherId,//默认用登录用户（可以独立让用户选择）
				CategoryName = this.CourseTypeComBox1.Text,
				CourseId = Convert.ToInt32(this.CourseNoLabel.Text)//这个字段在修改的时候必须要用
			};
			//【3】调用后台
			courseManager.ModifyCourse(course);
			this.panel1.Visible = false;

			//【4】同步显示修改后的信息（改进用户体验）（依然是从缓存中修改对象...)
			Course currentCourse = (from c in this.queryList where c.CourseId.Equals(course.CourseId) select c).First();
			currentCourse.CourseName = course.CourseName;
			currentCourse.CategoryName = course.CategoryName;
			currentCourse.CategoryId = course.CategoryId;
			currentCourse.CourseContent = course.CourseContent;
			currentCourse.Credit = course.Credit;
			currentCourse.ClassHour = course.ClassHour;

			this.CourseDataGridView.Refresh();//同步刷新dgv显示
		}
		//关闭修改窗口
		private void ExitChangeBtn_Click(object sender, EventArgs e)
		{
			this.panel1.Visible = false;
		}
		//删除课程
		private void DeleteCourseBtn_Click(object sender, EventArgs e)
		{
			if (this.CourseDataGridView.CurrentRow == null)
			{
				MessageBox.Show("请首先选择一行！", "删除提示");
				return;
			}
			//【1】获取当前选中行对应的ID
			int courseId = (int)this.CourseDataGridView.CurrentRow.Cells["CourseId"].Value;

			//【2】删除前确认
			DialogResult result = MessageBox.Show($"您确认要删除编号为：{courseId} 课程吗？", "删除确认", MessageBoxButtons.OKCancel,
				   MessageBoxIcon.Question);
			if (result == DialogResult.Cancel) return;
			//【3】从后台执行删除
			int deleletCount = courseManager.DeleteCourse(new Course { CourseId = courseId });

			//【4】从集合中删除
			//初学者可以使用前面的遍历方法(参考前面)
			//使用Linq查询或扩展方法
			this.queryList.Remove(this.queryList.Where(c => c.CourseId == courseId).First());

			//同步刷新显示
			this.CourseDataGridView.DataSource = null;
			this.CourseDataGridView.DataSource = this.queryList;
			this.QueryResultLabel.Text = this.queryList.Count.ToString();
		}

		private void CloseFrmCourseManage_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
